#!/bin/zsh

# Set wait in Get Info > Executable to Infinite.
# Do not put the installer in /Applications as Apple auto add a version here which may differ
# Apple process will kill the script one upgrade/instal is complete.  FileWave should launchd script to complete after reboot if still associated.  Events should be skipped on next run.

macos_instal_config="/usr/local/etc/com.filewave.macos_instal_config.plist"
instal_status=$(defaults read "$macos_instal_config" Status)
server_dns=$(defaults read /usr/local/etc/fwcld.plist server)
installer_location="/usr/local/etc/FileWaveInstallers/macos_installer/${installer_name}.app"

# Apple wipe custom logs in /private/var/log on upgrade.  Creating a custom log elsewhere...
# Moot point if option is set to erase

function echo_me {
        datef=$(date "+%Y-%m-%d %H:%M:%S.***")
        echo "$datef|main|CUSTOM|CLIENT|startosinstall $1" | tee -a /usr/local/etc/macos_instal.log
}

echo_me "Begin"
echo_me "Instal status: $instal_status"

# date_time=$(date -u +"%FT%TZ")

# Get CPU type, command is different between Intel and Apple M1
cpu_brand=$(sysctl machdep.cpu.brand_string | cut -d " " -f 2-)
echo_me "$cpu_brand"
arch_type=$(uname -m)

case $arch_type in

	"arm"*)
		cmd_prefix="/usr/bin/arch"
		cmd_arch="-arm64"
		cmd_user="--user"
		cmd_pass="--stdinpass"
	;;
	"x86"*)
		local_admin=""
		admin_pass=""
	;;
	*)
		echo "Unrecognised response for architecture: $arch_type"
		exit
	;;
esac

# Rest the Custom Field Flag and local value in plist
function reset_macos_instal_flag {

	echo_me "Resetting flag to NA"
	curl -s -k -X PATCH -H "Authorization: $api_key"  "https://${server_dns}/api/devices/v1/devices/${device_id}" -H  "accept: application/json" -H  "Content-Type: application/json" -d "{  \"custom_fields\": {\"macos_instal_flag\": \"NA\"}}" &>/dev/null
	defaults write "$macos_instal_config" Status NA
}

# Kill an already running upgrade process if there is one
startos_process=$(pgrep -lf startosinstall)

if [ $startos_process ]
then
	kill -9 ${startos_process%% *}
	echo_me "Found a version of macOS installer already running.  Killing task: ${startos_process#* }"
fi

# Run installer depending upon Custom Field Flag.  Erase should also clear certificate
# Consider adding another case and Custom Field value for erase and instal Custom PKG.
case $instal_status in

	"INSTAL")
		echo_me "Running $installer_location INSTAL"
		reset_macos_instal_flag		

		echo $admin_pass | $cmd_prefix $cmd_arch "${installer_location}/Contents/Resources/startosinstall" --agreetolicense --rebootdelay 20 $cmd_user $local_admin $cmd_pass --forcequitapps 2>&1
		exit_code=$?
	;;
	"ERASE")
		echo_me "Running $installer_location ERASE"
		reset_macos_instal_flag

		/usr/local/sbin/FileWave.app/Contents/MacOS/fwcld -clearCertificate -serverHost ${server_dns} -serverPort 20443
		echo $admin_pass | $cmd_prefix $cmd_arch "${installer_location}/Contents/Resources/startosinstall" --eraseinstall --agreetolicense --rebootdelay 20 $cmd_user $local_admin $cmd_pass --forcequitapps 2>&1
		exit_code=$?
	;;
	*)
		echo_me "Custom Field macOS Instal Flag set to: $instal_status"
		exit 0
	;;
esac

# Should not ever happen
if [ ! -e "$installer_location" ]
then
	# We should never be here
	echo_me "Nothing to instal and not retrying"
	exit 0
fi

# Allow script to exit with success, but report failure using the Custom Field Flag.
if [ $exit_code -ne 0 ]
then
	curl -s -k -X PATCH -H "Authorization: $api_key"  "https://${server_dns}/api/devices/v1/devices/${device_id}" -H  "accept: application/json" -H  "Content-Type: application/json" -d "{  \"custom_fields\": {\"macos_instal_flag\": \"FAILED\"}}" &>/dev/null
	echo_me "Installer $installer_location: FAILED"
	defaults write "$macos_instal_config" Status FAILED
	echo_me "startosinstall command failed with error code: $exit_code"
	exit 0
fi

# Stop fwcld interfering with the process if it takes a long time.  This should never be the case, but heh, here it is anyway
while [ $(pgrep -x startosinstall) ]
do
	echo_me "Sleeping"
	sleep 60
done

exit 0